< previous page page_486 next page >

Page 486
Continued
Listing 21.3
Public Function sGetINI(sINIFile As String, sSection As String, sKey _
                As String, sDefault As String) As String

    Dim sTemp As String * 256
    Dim nLength As Integer

    sTemp = Space$(256)
    nLength = GetPrivateProfileString(sSection, sKey, sDefault, sTemp, _
              255, sINIFile)
    sGetINI = Left$(sTemp, nLength)

End Function

Public Sub writeINI(sINIFile As String, sSection As String, sKey _
           As String, sValue As String)

    Dim n As Integer
    Dim sTemp As String

    sTemp = sValue

    'Replace any CR/LF characters with spaces
    For n = 1 To Len(sValue)
        If Mid$(sValue, n, 1) = vbCr Or Mid$(sValue, n, 1) = vbLf _
        Then Mid$(sValue, n) = " "
    Next n

    n = WritePrivateProfileString(sSection, sKey, sTemp, sINIFile)

End Sub
After the code in Listing 21.3 has been entered, you can now use the function sGetINI and the subroutine writeINI to easily read and write to an INI file. The following example shows how you can retrieve settings from an INI file for use at program startup.
Listing 21.4 INIEXAMPLE.ZIPUsing an INI File for Program Settings
Sub InitProgram()

Dim sINIFile As String
Dim sUserName As String
Dim nCount As Integer
Dim i As Integer

'Store the location of the INI file
sINIFile = App.Path & "\MYAPP.INI"

'Read the user name from the INI file
sUserName = sGetINI(sINIFile, "Settings", "UserName", "?")

If sUsername = "?"  Then
      'No user name was present  ask for it and save for next time
      sUserName = InputBox$("Enter your name please:")
      writeini sINIFile, "Settings","UserName",sUserName
End If

 
< previous page page_486 next page >